package com.siyoumi.sh.modules.jm;

import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.jm.entity.JmApiData;
import com.siyoumi.sh.modules.jm.entity.JmApiToken;
import com.siyoumi.util.*;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JmHandle
        extends JmHandleBase
        implements IHandle {
    @Override
    public JmApiData getJmApiData() {
        JmApiData data = new JmApiData();
        data.setApiRoot("https://sapi.uat.xiao-bo.com/");
        data.setSiteId("app.english");
        data.setJmApiTokens(getArrToken());

        return data;
    }

    @Override
    public void run() {
        if (getArrToken().size() <= 0) {
            log.error("未配置JM_TOKEN");
            return;
        }

        XLog.info(this.getClass(), "JmTask_BEGIN:" + XDate.toDateTimeString());

        Map<String, String> arrTask = getArrTask();

        StringBuilder sendMsg = new StringBuilder();
        sendMsg.append("**jm**\n\n");

        for (Map.Entry<String, String> task : arrTask.entrySet()) {
            String taskName = task.getKey();
            String returnStr = "";
            switch (taskName) {
                case "开宝箱":
                case "扭蛋":
                case "摇钱树":
                case "摇钱树2号":
                    returnStr = appSuperHandle(task);
                    break;
                default:
                    returnStr = commonHandle(task);
                    break;
            }

            sendMsg.append(returnStr);
        }

        //发信息
        sendMsg(sendMsg.toString());

        XLog.info(this.getClass(), "JmTask_END:" + XDate.toDateTimeString());
    }

    public Map<String, String> getArrTask() {
        Map<String, String> arr = new HashMap<>();
        arr.put("星球积分签到", "https://sapi.uat.xiao-bo.com/z_app/sign_in/web/zz_api__api__new__sign?site_id=app.english&wx_word=sign_in10001000&{wx_from}");
        arr.put("新星球积分签到", "https://sapi.uat.xiao-bo.com/z/app.english/__api_java__/z_app/sign_in_b/web/zz_api__api__new__sign?site_id=app.english&wx_word=sign_in10001000&{wx_from}");
//        arr.put("摇钱树", "sact-62fb312cd55cd-3584-9b8e-4f661cbd3ae5");
//        arr.put("摇钱树2号", "sact-62d66594d0417-30d0-aa41-62e05124acbc");
//        arr.put("扭蛋", "sact-627b24c483d45-3182-bb5f-10caf9b9dfae");
//        arr.put("开宝箱", "sact-627b24c483d45-3182-bb5f-10caf9b9dfae");
        return arr;
    }

    /**
     * token格式
     * name|wx_from|wx_from_enc&name2|wx_from2|wx_from_enc2
     */
    protected List<JmApiToken> getArrToken() {
        String token = System.getenv("JM_TOKEN");
        if (XStr.isNullOrEmpty(token)) {
            return new ArrayList<>();
        }

        List<JmApiToken> tokenArr = new ArrayList<>();
        String[] jmTokenArr = token.split("&");
        for (String s : jmTokenArr) {
            String[] dataArr = s.split("\\|");
            tokenArr.add(JmApiToken.getIns(dataArr[0], dataArr[1], dataArr[2]));
        }

        return tokenArr;
    }


    //通用任务处理
    protected String commonHandle(Map.Entry<String, String> task) {
        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        logAndSet(sendMsg, "**" + taskName + "** \n\n");

        List<JmApiToken> tokenArr = getArrToken();
        String url = task.getValue();
        for (JmApiToken token : tokenArr) {
            String userName = token.getName();
            String apiUrl = url.replace("{wx_from}", token.getWxFromQuery());
            XReturn r = requestApi(apiUrl);

            logAndSet(sendMsg, XStr.concat(userName, ":", r.getErrMsg(), "\n\n"));
        }

        return sendMsg.toString();
    }

    //超级活动
    protected String appSuperHandle(Map.Entry<String, String> task) {
        String apiUrlLunch = "https://sapi.uat.xiao-bo.com/z_app/star_act/web/zz_api__api_x__user_launch?" +
                "site_id=app.english&act_id={sact_id}&{wx_from}";
        apiUrlLunch = apiUrlLunch.replace("{sact_id}", task.getValue());

        String apiUrlChou = "https://sapi.uat.xiao-bo.com/z_app/star_act/web/zz_api__api_x__user_chou?" +
                "site_id=app.english&master_id={master_id}&{wx_from}";

        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        logAndSet(sendMsg, "**" + taskName + "** \n\n");

        List<JmApiToken> tokenArr = getArrToken();
        for (JmApiToken token : tokenArr) {
            String userName = token.getName();
            //发起
            String apiUrl = apiUrlLunch
                    .replace("{wx_from}", token.getWxFromQuery());
            XReturn r = null;
            while (true) {
                r = requestApi(apiUrl);
                logAndSet(sendMsg, XStr.concat(userName, "-发起:", r.getErrMsg(), "\n\n"));
                if (r.getErrCode() != -30301234) {
                    break;
                }
                logAndSet(sendMsg, "停1秒", true);
                XApp.sleep(1);
            }
            
            if (r.ok()) {
                Map data = r.getData("data");
                String samasterId = (String) data.get("samaster_id");

                apiUrl = apiUrlChou
                        .replace("{wx_from}", token.getWxFromQuery())
                        .replace("{master_id}", samasterId);
                while (true) {
                    r = requestApi(apiUrl);
                    logAndSet(sendMsg, XStr.concat(userName, "-抽奖:", r.getErrMsg(), "\n\n"));
                    if (r.getErrCode() != -30301234) {
                        break;
                    }
                    logAndSet(sendMsg, "停1秒", true);
                    XApp.sleep(1);
                }
            }
        }

        return sendMsg.toString();
    }
}
